<?php

/**
 * This is the model class for table "tbl_product".
 *
 * The followings are the available columns in table 'tbl_product':
 * @property integer $id
 * @property string $title
 * @property string $description
 * @property string $specs
 * @property double $price
 * @property string $brand
 * @property string $country
 * @property integer $is_present
 * @property string $code
 * @property integer $category_id
 * @property string $url
 * @property string $created_at
 * @property string $discount
 * @property string $image
 *
 * The followings are the available model relations:
 * @property Category $category
 */
class Product extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_product';
	}
	
	public $category_title;

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, category_id, price', 'required', 'message'=>'Поле "{attribute}" не может быть пустым.'),
            array('title', 'unique', 'message'=>'Товар с таким названием уже существует'),
			array('is_present, category_id', 'numerical', 'integerOnly'=>true),
			array('title, code, url', 'length', 'max'=>256),
			array('price, brand, country, discount', 'length', 'max'=>128),
			array('image', 'length', 'max'=>1024),
            array('price, discount', 'numerical', 'message'=>'{attribute} должна быть числом.'),
			array('created_at, price, description, specs', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, description, specs, price, brand, country, is_present, code, category_id, url, created_at, discount, image, category_title', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
            'orders'=>array(self::MANY_MANY, 'Order',
                'tbl_order_product(product_id, order_id)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Название',
			'description' => 'Описание (реклама)',
			'specs' => 'Характеристики',
			'price' => 'Цена',
			'brand' => 'Брэнд',
			'country' => 'Страна происхождения',
			'is_present' => 'В наличии',
			'code' => 'Артикул (штрих-код)',
			'category_id' => 'Категория',
			'category_title'=>'Категория',
			'url' => 'Url',
			'created_at' => 'Дата создания',
			'discount' => 'Скидка',
			'image' => 'Изображение',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
		
		$criteria->with=array('category');
        //$criteria->together = true;

		$criteria->compare('id',$this->id);
		$criteria->compare('t.title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('specs',$this->specs,true);
		$criteria->compare('price',$this->price,true);
		$criteria->compare('brand',$this->brand,true);
		$criteria->compare('country',$this->country,true);
		$criteria->compare('is_present',$this->is_present);
		$criteria->compare('code',$this->code,true);
		$criteria->compare('category_id',$this->category_id);
		$criteria->compare('url',$this->url,true);
		$criteria->compare('created_at', $this->created_at,true);
		$criteria->compare('discount',$this->discount,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('category.title',$this->category_title,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array(
				'attributes'=>array(
					'category_title'=>array(
						'asc'=>'category.title',
						'desc'=>'category.title DESC',
					),
					'*',
				),
			)
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Product the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}
